#ifndef __TIMER_HPP__
#define __TIMER_HPP__

#include "peripheral.h"
#include "sync-queue.hpp"
#include <vector>
#include <thread>
#include <chrono>

class Timer
{
public:
    std::thread thread_handle;

    SyncQueue<IORequest> io_channel;
    std::vector<std::shared_ptr<SyncQueue<Interupt>>> interrupt_channels;

    Timer(const std::vector<std::shared_ptr<SyncQueue<Interupt>>>& iv) : interrupt_channels(iv) {}

    void run(int milli_time)
    {
        thread_handle = std::thread([this, milli_time](){
            auto start = std::chrono::high_resolution_clock::now();

            while(1)
            {
                auto end = std::chrono::high_resolution_clock::now();
                auto dur = end - start;



                if(dur.count() / 1000000 > milli_time)
                {
                    start = std::chrono::high_resolution_clock::now();
                    for(const auto& interrupt_ref: this->interrupt_channels)
                    {
                        interrupt_ref->push(Interupt{0,0,0,0,Interupt::Type::TIME_OUT});
                    }
                }

                if(auto tmp = this->io_channel.try_pop())
                {
                    if(tmp->type==IORequest::Type::SHUTDOWN)
                    {
                        return;
                    }
                }
            }
        });
    }
};

#endif